package com.browsesoft.htmlcomponent;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;
import com.browsesoft.ManagerGroup;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.workflow.support.sortInterface;

/**
 * 单表数据维护表格组件
 */
public class HTMLDBTableModel implements HTMLTableModel, sortInterface {
	/**
	 * Model所对应的component
	 */
	protected HTMLBasicComponent component = null;

	/**
	 * 数据库的表名
	 */
	protected String tableName = null;

	/**
	 * 从表中取得的所有数据
	 */
	protected String datas[][] = null;

	/**
	 * 取数据时的sql语句
	 */
	protected String sql = null;

	/**
	 * 要显示的所有字段中文名
	 */
	protected LinkedList cnames = new LinkedList();

	protected String sortname = "";

	/**
	 * 要显示的所有字段英文名
	 */
	protected LinkedList enames = new LinkedList();

	/**
	 * 编辑的模板名
	 */
	protected String form = null;

	/**
	 * 父节点号
	 */
	protected String parentID = null;

	protected boolean orderby = false;

	protected boolean issort = false;

	// 查询条件
	private String condition = null;

	// 升序，降序
	private String order;

	private String orderByName;

	/**
	 * 初始化model
	 */
	public void init(HttpServletRequest request) throws Exception {
		// 得到模板中的form元素中的form属性值，用来
		Element formElement = (Element) component.getPage().getDocument()
				.getElementsByTagName("form").item(0);
		this.orderByName = formElement.getAttribute("orderbyname");
		this.order = formElement.getAttribute("order");
		form = formElement.getAttribute("form");
		// 如果form属性值存在
		if (form != null && !form.equals("")) {
			// 得到模板管理嚣
			TemplateManager manager = (TemplateManager) ManagerGroup
					.getManagerGroup().getManager("template");
			// 由form属性值生成页面
			Template t = manager.getTemplateByName(form);
			// 得到模板文档,
			Document document = t.getDocument();
			// 解析文档,找出需要处理的根元素
			Element root = (Element) document.getElementsByTagName("body")
					.item(0);
			// 找到所有显示的组件
			LinkedList v = ExtendElement.findElements(root, "show", "show");
			// 生成SQL语句
			sql = "select *";
			for (int i = 0; i < v.size(); i++) {
				Element element = (Element) v.get(i);
				enames.add(element.getAttribute("name"));
				cnames.add(element.getAttribute("cname"));
			}
			// 找到数据库表名
			tableName = ((Element) document.getElementsByTagName("form")
					.item(0)).getAttribute("name");
			sql += " from " + tableName;
		}
	}

	/**
	 * 得到列数
	 * 
	 * @return 列数
	 */
	public int getColumnCount() {
		return cnames.size() + 2;
	}

	/**
	 * 得到列的名称
	 * 
	 * @param index
	 *            列号
	 * @return 列的名称
	 */
	public String getColumnName(int index) {
		if (index < cnames.size()) {
			return (String) cnames.get(index);
		} else {
			return "";
		}
	}

	/**
	 * 得到列的英文名
	 * 
	 * @param index
	 *            列号
	 * @return 列的英文名
	 */
	public String getColumnEname(int index) {
		if (index < enames.size()) {
			return (String) enames.get(index);
		} else {
			return "";
		}
	}

	public Object getDatas() {
		return null;
	}

	/**
	 * 得到行数
	 * 
	 * @return 行数
	 */
	public int getRowCount() {
		return datas.length - 1;
	}

	/**
	 * 设置传递的参数
	 * 
	 * @param request
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 得到条件
		if (parentID == null) {
			parentID = request.getParameter("point");
		}
		// 保持原有SQL非条件部分不动
		String executeSQL = new String(sql);
		// 有必备条件
		if (parentID != null) {
			// 添加必备条件
			executeSQL += " where processid=" + "'" + parentID + "'";
			// 补上用户输入的条件
			if (condition != null && !condition.equals("")) {
				executeSQL += " and " + condition;
			}
		}
		// 没有必备条件
		else {
			// 添加用户输入的条件
			if (condition != null && !condition.equals("")) {
				executeSQL += " where " + condition;
			}
		}
		if (order != null && !order.equals("") && orderByName != null
				&& !orderByName.equals("")) {
			executeSQL += " group by " + this.orderByName + " " + this.order;
		}
		try {
			// 得到结果
			datas = DBTools.executeQueryWithTableHead(executeSQL);
		} catch (Exception e) {
			datas = new String[1][0];
		}
		/*
		 * String tt =
		 * request.getParameter(component.getName().concat(".sort")); if (tt !=
		 * null) { String temp = new String(tt.getBytes("ISO8859-1")); temp =
		 * temp.substring(temp.lastIndexOf(".") + 1); if (! (
		 * (sortInterface)this).getOrderBy()) { (
		 * (sortInterface)this).sort(temp); ( (sortInterface)this).setOrderBy(); }
		 * else if ( ( (sortInterface)this).getOrderBy()) { (
		 * (sortInterface)this).reverseSort(temp); (
		 * (sortInterface)this).setOrderBy(); } }
		 */
	}

	/**
	 * 设置查询条件
	 */
	public void setCondition(String condition) {
			this.condition = condition;
	}

	/**
	 * 得到查询条件
	 */
	public String getCondition() {
		return this.condition;
	}

	/**
	 * 得到某列的操作类型
	 * 
	 * @return 类型
	 */
	public String getType(int col) {
		if (col < cnames.size()) {
			return "td";
		} else if (col == cnames.size()) {
			return "modify";
		} else if (col == cnames.size() + 1) {
			return "delete";
		}
		return null;
	}

	/**
	 * 修改单元值
	 */
	public void modifyCellValue(Element td, Document doc, int row, int col) {
		try {
			// 显示名字
			if (col < cnames.size()) {
				if (this.getsort() && this.getOrderBy()) {
					this.sort(this.getsortname());
				} else if (this.getsort() && !this.getOrderBy()) {
					this.reverseSort(this.getsortname());
				}
				// 得到链接
				LinkedList nl = ExtendElement.findElements(td, "type", "link");
				if (nl.size() != 0) {
					Element link = (Element) nl.get(0);
					String value = link.getAttribute("onclick");
					int index = DBTools.indexOf(datas[0], "id");
					value = value.replaceAll("point=", "point="
							+ datas[row + 1][index]);
					link.setAttribute("onclick", value);
				}
				int index = DBTools.indexOf(datas[0], (String) enames.get(col));
				if (index != -1) {
					ExtendElement.replaceElementContext(td, doc
							.createTextNode(datas[row + 1][index]));
				} else {
					ExtendElement.replaceElementContext(td, doc
							.createTextNode(""));
				}
			}
			// 修改
			else if (col == cnames.size()) {
				if (this.getsort() && this.getOrderBy()) {
					this.sort(this.getsortname());
				} else if (this.getsort() && !this.getOrderBy()) {
					this.reverseSort(this.getsortname());
				}
				Element e = (Element) ExtendElement.findElements(td, "type",
						"link").get(0);
				String str = e.getAttribute("onclick");
				int index = DBTools.indexOf(datas[0], "id");
				str = str.replaceAll("id=", "id=" + datas[row + 1][index]);
				// 设置修改的模板
				str = str.replaceAll("templatename=", "templatename=" + form);
				e.setAttribute("onclick", str);
			}
			// 删除
			else if (col == cnames.size() + 1) {
				if (this.getsort() && this.getOrderBy()) {
					this.sort(this.getsortname());
				} else if (this.getsort() && !this.getOrderBy()) {
					this.reverseSort(this.getsortname());
				}
				Element e = (Element) ExtendElement.findElements(td, "type",
						"link").get(0);
				String str = e.getAttribute("onclick");
				int index = DBTools.indexOf(datas[0], "id");
				str = str.replaceAll("id=", "id=" + datas[row + 1][index]);
				// 设置删除的表名
				str = str.replaceAll("tablename=", "tablename=" + tableName);
				e.setAttribute("onclick", str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
		this.component = component;
	}

	/**
	 * 排序
	 * 
	 * @param key
	 *            关键字
	 */
	public void sort(String key) {
		this.setsort();
		this.sortname = key;
		int index = 0;
		String className = this.getClass().getName();
		className = className.substring(className.lastIndexOf(".") + 1);
		for (int i = 0; i < this.getColumnCount(); i++) {
			if (key.equals(className + i)) {
				for (int j = 0; j < datas[0].length; j++) {
					if (((String) enames.get(i)).toUpperCase().equals(
							datas[0][j])) {
						index = j;
						break;
					}
				}
				break;
			}
		}
		String[][] tempdatas = new String[datas.length - 1][datas[0].length];
		for (int i = 0; i < datas.length - 1; i++) {
			for (int j = 0; j < datas[0].length; j++) {
				tempdatas[i][j] = datas[i + 1][j];
			}
		}
		Arrays.sort(tempdatas, new StringComparator(index));
		for (int i = 1; i < datas.length; i++) {
			for (int j = 0; j < datas[0].length; j++) {
				datas[i][j] = tempdatas[i - 1][j];
			}
		}
	}

	public boolean getOrderBy() {
		return this.orderby;
	}

	public void setOrderBy() {
		this.orderby = !this.orderby;
	}

	public void reverseSort(String key) {
		this.sort(key);
		for (int i = 1; i <= datas.length / 2; i++) {
			String[] temp = datas[i];
			datas[i] = datas[datas.length - i];
			datas[datas.length - i] = temp;
		}
	}

	public void setsort() {
		this.issort = true;
	}

	public boolean getsort() {
		return this.issort;
	}

	public String getsortname() {
		return this.sortname;
	}

	/**
	 * 模型更新页面元素
	 * 
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}
}

/**
 * 字串二维数组比较类
 */
class StringComparator implements Comparator {
	int index = 0;

	public StringComparator(int i) {
		index = i;
	}

	public int compare(Object str1, Object str2) {
		if (((String[]) str1)[index].compareTo(((String[]) str2)[index]) >= 0) {
			return 1;
		} else {
			return -1;
		}
	}

	public boolean equals(Object obj) {
		return false;
	}
}
